require 'open-uri'

class FonmapController < ApplicationController

  def index
  end

  def getMarkers
    sWLat = @params[:input][:sWLat]
    sWLng = @params[:input][:sWLng]
    nELat = @params[:input][:nELat]
    nELng = @params[:input][:nELng]
    zoom = @params[:input][:zoom]
    
    require 'net/http'
    Net::HTTP.version_1_2
    
    param = "action=getMarkers"
    param = param + "&sWLat=" + sWLat
    param = param + "&sWLng=" + sWLng
    param = param + "&nELat=" + nELat
    param = param + "&nELng=" + nELng
    param = param + "&zoom=" + zoom
    param = param + "&lang=" + "jp"
    
    Net::HTTP.start('maps.fon.com', 80) {|http|
      response = http.post("/index.php",
                            param + '&order=undefined&viewon=true&viewoff=true&viewus=true&viewret=true&max=200')
                            puts(response.body)
      @json = response.body
    }
  end

  def getUstreamJson
    channel = @params[:input][:channel]
    content = ''
    open('http://ustream.tv/channel/' + channel) do |f|
      content = f.read
    end
    i1 = content.index('Embed:')
    i2 = content.index('value=\'', i1)
    i3 = i2 + 7
    i4 = content.index('\'', i3)
    tag = content[i3...i4]
    tag.sub! /width="[0-9]+"/, "id=\"ustream_#{channel}\""
    tag.sub! /height="[0-9]+"/, ''
    puts tag
    render_to_json([tag], 'ustream_tag')
  end

  def getTwitter
    twitterId = @params[:input][:twitterId]
    
    require 'net/http'
    Net::HTTP.version_1_2
    
    Net::HTTP.start('twitter.com', 80) {|http|
      response = http.get('/statuses/user_timeline/' + twitterId + '.json')
                            puts(response.body)
      @json = response.body
    }
  end
  
  private
  def render_to_json(models, name)
    json = to_json(models, name)
    puts json
    render :json => json
  end

  def to_json(models, name)
    obj = {:status => 'ok', name => models}
    obj.to_json
   end

 end
